import { calculateAngleBetween3Points } from './math';
import { type LineFeature, ShapeTool } from './shape';

export class AngleTool extends ShapeTool {
  addLabel = (
    id: string,
    coords: GeoJSON.Position[],
    angles: number[] = [],
  ) => {
    const labels = angles.map((a) => `${a.toFixed(2)}°`);
    this.createLabels(id, labels, coords);
  };

  handleCreate = (feature: GeoJSON.Feature) => {
    const line = feature as LineFeature;
    const coords = line.geometry.coordinates;

    this.addId(feature.id as string);

    // 少于3个点不处理
    if (coords.length < 3) return;

    const angs = [];
    const poss = [];
    // 从第二个点开始计算，到倒数第二个点结束
    for (let i = 1; i < coords.length - 1; i++) {
      // 转换为角度
      const angleDeg = calculateAngleBetween3Points(
        coords[i - 1],
        coords[i],
        coords[i + 1],
      );
      angs.push(angleDeg);
      poss.push(coords[i]);
    }
    // 在顶点位置显示角度
    this.addLabel(feature.id as string, poss, angs);

    this.draw?.setDrawingMode('simple_select');
  };

  handleDelete = (feature: GeoJSON.Feature) => this.delId(feature.id as string);

  validate = (feature: GeoJSON.Feature) => {
    const isAngle = this.shapeIds.includes(feature.id as string);
    return this.draw?.drawingMode === 'draw_angle' || isAngle;
  };
}
